<template>
  <div
    v-loading="exportLoading"
    element-loading-text="数据导出中"
    element-loading-spinner="el-icon-loading"
  >
    <el-form ref="searchForm" :inline="true" :model="page" style="margin-top: 20px;">
      <el-form-item label="IP">
        <el-input v-model="page.params.logIp" clearable placeholder="请求IP" />
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="page.params.logStatus" placeholder="请选择状态" clearable filterable @clear="clearSelect">
          <el-option label="正常" :value="1" />
          <el-option label="异常" :value="0" />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="createdTime"
          type="datetimerange"
          :picker-options="pickerOptions"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          align="right"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">查询</el-button>
      </el-form-item>
    </el-form>
    <el-divider />
    <el-button type="danger" size="mini" class="addBtn" @click="handlerDeleteByIds">批量删除日志</el-button>
    <el-button type="primary" size="mini" class="addBtn" @click="handlerExport">导出日志</el-button>
    <el-button type="danger" :loading="deleteAllLoading" size="mini" class="addBtn" @click="handlerDeleteAll">清空日志</el-button>
    <el-table
      v-loading="loading"
      :data="page.list"
      border
      style="width: 100%"
      element-loading-text="数据加载中"
      element-loading-spinner="el-icon-loading"
      @sort-change="handlerSortChange"
      @selection-change="handlerSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column type="expand" label="展开" width="55">
        <template slot-scope="props">
          <el-form label-position="left" inline-message class="demo-table-expand">
            <el-form-item label="请求IP">
              <span class="sp">{{ props.row.logIp }}</span>
            </el-form-item>
            <el-form-item label="请求状态">
              <span class="sp">{{ props.row.logStatus }}</span>
            </el-form-item>
            <el-form-item label="请求时间">
              <span class="sp">{{ props.row.createdTime }}</span>
            </el-form-item>
            <el-form-item label="请求参数">
              <span class="sp">{{ props.row.logParams }}</span>
            </el-form-item>
            <el-form-item label="日志信息">
              <span class="sp">{{ props.row.logMessage }}</span>
            </el-form-item>
            <el-form-item label="返回参数">
              <span class="sp">{{ props.row.logResult }}</span>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column prop="logId" label="编号" width="55" />
      <el-table-column prop="logIp" label="请求IP地址" sortable="custom" />
      <el-table-column prop="logUrl" label="请求地址" show-overflow-tooltip />
      <el-table-column prop="logParams" label="请求参数" width="180" show-overflow-tooltip />
      <el-table-column prop="logStatus" label="请求状态" width="80">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.logStatus===1" type="success">正常</el-tag>
          <el-tag v-else type="danger">异常</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="logMessage" label="日志信息" width="300px" show-overflow-tooltip />
      <el-table-column prop="logMethod" label="请求方法" />
      <el-table-column prop="logTime" label="相应时间" />
      <el-table-column prop="logResult" label="返回值" show-overflow-tooltip />
      <el-table-column prop="createdTime" label="创建时间" sortable="custom" />
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-dropdown trigger="hover">
            <el-button size="mini" type="primary">
              操作<i class="el-icon-arrow-down el-icon--right" />
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item>
                <el-button size="mini" type="danger" @click="handlerDelete(scope.row.logId)">删除</el-button>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>

      </el-table-column>
    </el-table>
    <el-pagination
      :current-page="page.currentPage"
      :page-sizes="[5, 10, 15, 20, 200]"
      :page-size="page.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="page.countTotal"
      class="pagination-bottom"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
</template>

<script>
import logApi from '@/api/log'
export default {
  name: 'LogList',
  components: {

  },
  data() {
    return {
      // 数据列表
      drawer: false,
      dialogVisible: false,
      loading: true,
      page: {
        currentPage: 0, // 当前页
        pageSize: 10, // 页面大小
        pageTotal: 0, // 总页数
        countTotal: 0, // 总条数
        sortColumn: '', // 排序字段
        sortMethod: 'asc', // 排序方法
        list: [], // 数据
        params: {} // 条件查询参数
      },
      deleteAllLoading: false,
      log: {},
      multipleSelection: [],
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      },
      createdTime: [],
      exportLoading: false // 数据加载
    }
  },
  watch: {
    'createdTime': function(newVal, oldValue) {
      if (newVal != null) {
        this.page.params.beginTime = newVal[0].toLocaleDateString().replace(new RegExp('/', 'g'), '-') + ' ' + newVal[0].toTimeString().substring(0, 8)
        this.page.params.endTime = newVal[1].toLocaleDateString().replace(new RegExp('/', 'g'), '-') + ' ' + newVal[1].toTimeString().substring(0, 8)
      } else {
        delete this.page.params.createdTime
        delete this.page.params.beginTime
        delete this.page.params.endTime
      }
    }
  },
  created() {
    this.getLogList()
  },
  methods: {
    // 清空日志
    handlerDeleteAll() {
      this.$confirm('此操作将清空日志, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteAllLoading = true
        logApi.deleteAll().then(res => {
          if (res.code === 200) {
            this.deleteAllLoading = false
            this.getLogList()
          } else {
            this.deleteAllLoading = false
          }
        }).catch(() => {
          this.deleteAllLoading = false
        })
      })
    },
    handleSizeChange(val) {
      this.page.pageSize = val
      this.getLogList()
    },
    handleCurrentChange(val) {
      this.page.currentPage = val
      this.getLogList()
    },
    // 多选框事件
    handlerSelectionChange(val) {
      this.multipleSelection = []
      val.forEach(res => {
        this.multipleSelection.push(res.logId)
      })
    },
    // 处理分类
    handlerSortChange(e) {
      this.page.sortMethod = e.order
      this.page.sortColumn = e.prop
      this.getLogList()
    },
    getLogList() {
      this.loading = true
      this.page.list = []
      logApi.getByPage(this.page).then(res => {
        if (res.code === 200) {
          this.page = res.data
          this.loading = false
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    handlerExport() {
      this.exportLoading = true
      logApi.export().then(res => {
        var blob = new Blob([res], { type: 'application/vnd.ms-excel' })
        var eLink = document.createElement('a')
        eLink.download = '系统日志.xlsx'
        eLink.href = URL.createObjectURL(blob)
        eLink.style.display = 'none'
        document.body.appendChild(eLink)
        eLink.click()
        document.removeChild(eLink)
        URL.revokeObjectURL(eLink.href)
        this.exportLoading = false
      }).catch(() => {
        this.exportLoading = false
      })
    },
    onSubmit() {
      this.getLogList()
    },
    clearSelect() {
      delete this.page.params.logStatus
    },
    handlerDelete(id) {
      this.$confirm('此操作将永久删除该分类, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        logApi.deleteById(id).then(res => {
          if (res.code === 200) {
            this.$message.success(res.msg)
          }
          this.getLogList()
        })
      })
    },
    handlerDeleteByIds() {
      this.$confirm('此操作为批量删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (this.multipleSelection.length === 0) {
          this.$message.error('未选择')
        }
        const loading = this.$loading({
          lock: true,
          text: '删除中请稍后',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        logApi.deleteByIds(this.multipleSelection).then(res => {
          if (res.code === 200) {
            this.$message.success(res.msg)
            loading.close()
          }
          this.getLogList()
        }).then(() => {
          loading.close()
        })
      })
    }
  }
}
</script>
<style scoped lang="scss">
  .demo-table-expand {
    font-size: 0;
  }
  .demo-table-expand label {
    width: 90px;
    color: #99a9bf;
  }
  .sp{
    font-size: 15px;
  }
  .demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 50%;
  }
</style>
